package control

import (
	"github.com/gin-gonic/gin"
	"myself/constants"
	"myself/logic"
	"myself/rsp"
	"myself/util"
	"strings"
)

type accountIn struct {
	AccountId string `json:"account_id"`
	Password  string `json:"password"`
	RealName  string `json:"real_name"`
}

func Registered(context *gin.Context) {
	json := &accountIn{}
	context.BindJSON(json)
	accountLogic := logic.NewAccountLogic()
	isExist := accountLogic.HasAccountByAccountId(json.AccountId)
	if isExist == true {
		rsp.FailResponse(context, "账号已存在", constants.FailCode)
		return
	}
	err := accountLogic.CreateAccount(json.AccountId, json.Password, json.RealName)
	if err != nil {
		rsp.FailResponse(context, "注册失败", constants.FailCode)
	} else {
		rsp.SuccessResponse(context, nil)
	}
}

func Login(context *gin.Context) {
	json := &accountIn{}
	context.BindJSON(json)
	accountLogic := logic.NewAccountLogic()
	isExist := accountLogic.HasAccountByAccountId(json.AccountId)
	if !isExist {
		rsp.FailResponse(context, "账号不存在", constants.FailCode)
		return
	}
	token, err := accountLogic.Login(json.AccountId, json.Password)
	if err != nil {
		rsp.FailResponse(context, "登录失败", constants.FailCode)
		return
	}
	rsp.SuccessResponse(context, map[string]string{"token": token})
}

func CheckLoginState(context *gin.Context, token string) *string {
	if strings.Compare("", token) == 0 {
		rsp.FailResponse(context, "请登录", constants.UnauthorizedCode)
		context.Abort()
		return nil
	}

	claims, err := util.ParseToken(token)
	if err != nil {
		rsp.FailResponse(context, err.Error(), constants.UnauthorizedCode)
		context.Abort()
		return nil
	}
	return &claims.AccountId
}

func LoginEffective(context *gin.Context) {
	rsp.SuccessResponse(context, constants.SuccessCode)
}
